﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Servidor.Interface;
using System.IO;
using System.Xml.Serialization;
using TiposComuns.Objectos;
using Servidor.Objectos;
using Servidor.Objectos.RemoteActions;
using Servidor.Objectos.Actions;
using Servidor.Objectos.Pesquisa;
using System.Runtime.Remoting.Channels;
using System.Collections;
using System.Runtime.Remoting.Channels.Tcp;
using Servidor.WebServices;
using System.Runtime.Remoting;
using System.Runtime.Serialization.Formatters;
using System.Net;

namespace Servidor
{
    public class Temp
    {
        private Dictionary<string, string> dic = new Dictionary<string, string>();
    }

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// arg 0 -> username
        /// arg 1 -> porta
        /// arg 2 -> id servidor (1,2,3)
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Init());
            }
            else
            {   //iniciar com a linha de comandos
                try
                {
                    string strHostName = Dns.GetHostName();
                    string end = ""; //endereço tcp
                    IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
                    IPAddress[] addr = ipEntry.AddressList;


                    string[] s = args[0].Split(",".ToCharArray());
                    int id = Int32.Parse(s[2]); //id do servidor

                    foreach (IPAddress ip in addr)
                    {
                        if (ip.GetAddressBytes().Length == 4)
                        {
                            end = "tcp://" + ip.ToString();
                        }
                    }
                    Person person = new Person(s[0], new Address(end, Int32.Parse(s[1])));
                    State state = Proxy.GetInstance().Init((id - 1), person);
                    
                    
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Servidor.Interface.StateForm servform = new Servidor.Interface.StateForm(state, id, person, "");
                    servform.Text = person.Username + " " + (Int32.Parse(s[1]) + id) + " (S" + id + ")";
                    Application.Run(servform);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Erro: "+e.Message);
                }
            }
        }
    }
}
